Custom Authentication এবং Authorization Filter কনফিগার করা

Java Technologies - স্প্রিং সিকিউরিটি (Spring Security) - Spring Security এর জন্য Custom Filters
197

স্প্রিং সিকিউরিটিতে Custom Authentication এবং Custom Authorization ফিল্টার তৈরি করা সম্ভব, যা আপনার নির্দিষ্ট নিরাপত্তা নীতির উপর ভিত্তি করে কাজ করতে পারে। এই ফিল্টারগুলি আপনাকে বিশেষভাবে ক্লায়েন্টের অনুরোধের উপর কাস্টম অথেনটিকেশন এবং অথরাইজেশন চেক করার অনুমতি দেয়।

এখানে আমরা Custom Authentication Filter এবং Custom Authorization Filter তৈরি করার একটি উদাহরণ দেখব এবং কিভাবে এগুলি স্প্রিং সিকিউরিটির সিকিউরিটি কনফিগারেশনে যুক্ত করা যায় তা দেখানো হবে।


১. Custom Authentication Filter

Custom Authentication Filter তৈরি করার মাধ্যমে, আপনি নিজের প্রয়োজন অনুযায়ী HTTP অনুরোধ থেকে ইউজারের অথেনটিকেশন হ্যান্ডেল করতে পারেন। সাধারণত JWT (JSON Web Token) বা কোনো কাস্টম অথেনটিকেশন স্কিমা ব্যবহার করে এফিল্টার কাজ করে।

Step 1: Custom Authentication Filter তৈরি করুন

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class CustomAuthenticationFilter extends OncePerRequestFilter {

    private final AuthenticationManager authenticationManager;

    public CustomAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, javax.servlet.FilterChain chain)
            throws ServletException, IOException {

        String token = request.getHeader("Authorization");

        if (token != null && token.startsWith("Bearer ")) {
            String jwt = token.substring(7); // Extract JWT token

            // Normally here, you would parse and validate the JWT token to get the user details
            String username = "extracted_username_from_jwt"; // Example: extracted from JWT
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(username, null, null); // Use roles if needed

            Authentication authentication = authenticationManager.authenticate(authenticationToken);

            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        chain.doFilter(request, response);
    }
}

ব্যাখ্যা:

  • OncePerRequestFilter: এটি স্প্রিং সিকিউরিটির একটি বেস ক্লাস যা একবারে একবার একটি রিকোয়েস্ট প্রসেস করে।
  • JWT: এখানে আমরা ধরে নিয়েছি যে আপনি JWT টোকেন থেকে ইউজারের নাম সংগ্রহ করছেন, তবে এটি যেকোনো ধরনের কাস্টম অথেনটিকেশন হতে পারে (যেমন, ইউজারনেম-পাসওয়ার্ড, API কিওয়া ইত্যাদি)।
  • AuthenticationManager: এটি একটি ইন্টারফেস যা ইউজারের অথেনটিকেশন নিশ্চিত করে।

Step 2: Security Configuration এ Filter যোগ করা

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final AuthenticationManager authenticationManager;

    public SecurityConfig(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilter(new CustomAuthenticationFilter(authenticationManager)) // Add custom authentication filter
            .authorizeRequests()
            .antMatchers("/public/**").permitAll()  // Public access endpoints
            .anyRequest().authenticated();  // All other requests need authentication
    }
}

২. Custom Authorization Filter

Custom Authorization Filter তৈরি করার মাধ্যমে, আপনি নিশ্চিত করতে পারেন যে শুধুমাত্র অনুমোদিত ইউজাররা বিশেষ রিসোর্সে অ্যাক্সেস পাবে। এটি সাধারণত Role-based বা Permission-based অ্যাক্সেস কন্ট্রোল ইমপ্লিমেন্ট করতে ব্যবহৃত হয়।

Step 1: Custom Authorization Filter তৈরি করুন

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class CustomAuthorizationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, javax.servlet.FilterChain chain)
            throws ServletException, IOException {

        Authentication authentication = (Authentication) SecurityContextHolder.getContext().getAuthentication();

        if (authentication != null && authentication.isAuthenticated()) {
            // Here you can implement your authorization logic
            // For example: check if the user has required roles/permissions to access the resource

            if (!hasPermission(authentication, request.getRequestURI())) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "You do not have permission to access this resource");
                return;
            }
        }

        chain.doFilter(request, response);
    }

    // Example permission check (this can be customized based on your needs)
    private boolean hasPermission(Authentication authentication, String uri) {
        // Check user roles/permissions
        if (authentication.getAuthorities().stream().anyMatch(role -> role.getAuthority().equals("ROLE_ADMIN"))) {
            return true; // If the user has ADMIN role, grant access
        }
        return false; // Otherwise, deny access
    }
}

ব্যাখ্যা:

  • OncePerRequestFilter: এটি প্রতি HTTP অনুরোধের জন্য একবার চালিত হয়।
  • hasPermission: একটি উদাহরণ ফাংশন যেখানে আপনি ব্যবহারকারীর রোল বা পারমিশন যাচাই করতে পারেন।
  • response.sendError(HttpServletResponse.SC_FORBIDDEN, "You do not have permission to access this resource");: যদি ব্যবহারকারীর অনুমতি না থাকে, তাহলে তাকে 403 Forbidden ত্রুটি পাঠানো হয়।

Step 2: Security Configuration এ Authorization Filter যোগ করা

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilter(new CustomAuthorizationFilter()) // Add custom authorization filter
            .authorizeRequests()
            .antMatchers("/public/**").permitAll()  // Public access endpoints
            .anyRequest().authenticated();  // All other requests need authentication
    }
}

৩. কাস্টম অথেনটিকেশন এবং অথরাইজেশন ফিল্টার ব্যবহার করার উপকারিতা:

  1. কাস্টম অথেনটিকেশন:
    • আপনার নিজের অথেনটিকেশন পদ্ধতি ব্যবহার করে ইউজারের পরিচয় যাচাই করতে পারবেন।
    • উদাহরণস্বরূপ, JWT, OAuth, বা অন্য কোনো কাস্টম অথেনটিকেশন স্কিমা।
  2. কাস্টম অথরাইজেশন:
    • ইউজারের রোল বা পারমিশন যাচাই করে অ্যাক্সেস কন্ট্রোল করতে পারবেন।
    • আপনি বিভিন্ন রিসোর্স বা API এ একাধিক রোল বা পারমিশন যাচাই করতে পারেন, যেমন ROLE_ADMIN বা WRITE_PERMISSION
  3. নিরাপত্তা:
    • আপনার নিরাপত্তা নীতির সাথে সঙ্গতিপূর্ণ কাস্টম অথেনটিকেশন এবং অথরাইজেশন পদ্ধতি তৈরি করতে পারবেন।
    • এটি ইউজারের অ্যাক্সেস নিয়ন্ত্রণে আরও সূক্ষ্মতা এবং নমনীয়তা এনে দেয়।

উপসংহার

স্প্রিং সিকিউরিটিতে Custom Authentication Filter এবং Custom Authorization Filter তৈরি করা খুবই কার্যকরী এবং শক্তিশালী নিরাপত্তা ব্যবস্থা। কাস্টম অথেনটিকেশন ফিল্টার ইউজারের পরিচয় যাচাই করে, এবং কাস্টম অথরাইজেশন ফিল্টার ইউজারের অনুমতি যাচাই করে। আপনি যেভাবে চাচ্ছেন আপনার নিরাপত্তা নিয়ন্ত্রণ ব্যবস্থা সেটআপ করতে পারবেন, এবং এটি স্প্রিং সিকিউরিটির স্ট্যান্ডার্ড নিরাপত্তা ফিচারের সাথে একত্রে কাজ করবে।

Content added By
Promotion
NEW SATT AI এখন আপনাকে সাহায্য করতে পারে।

Are you sure to start over?

Loading...